package com.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;

/**
 * Created by nihao on 2014/9/16.
 */
public class HTRinger {
    private static final String TAG = "HTRinger";
    private static final String RINGING_FILE = "sound/ringing.mp3";
    AudioManager audioManager;
    boolean isPlaying = false;
    boolean isSpeakerOn = false;
    MediaPlayer player = null;
    int currentPosition = 0;

    public HTRinger(Context ctx) {
        audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
    }

    public void play(Context ctx) {
        HT_Log.d(TAG, "startRinging:speaker:" + isSpeakerOn);
        try {
            if (isPlaying) {
                HT_Log.w(TAG, "is already playing");
                return;
            }
            if (player == null) {
                player = new MediaPlayer();
            }

//            player.setVolume(0, 1);
            int streameType = AudioManager.STREAM_RING;
            if (isSpeakerOn) {
                streameType = AudioManager.STREAM_RING;

                player.setAudioStreamType(streameType);

//                audioManager.setStreamVolume(AudioManager.STREAM_RING, audioManager.getStreamMaxVolume(AudioManager.STREAM_RING), 0);
                audioManager.setSpeakerphoneOn(true);
                audioManager.setMode(AudioManager.MODE_RINGTONE);
            } else {
                streameType = AudioManager.STREAM_VOICE_CALL;
                player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

//                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
//                        audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);
                audioManager.setSpeakerphoneOn(false);
                audioManager.setMode(AudioManager.MODE_IN_CALL);
            }


            player.reset();


            AssetManager assetManager = ctx.getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(RINGING_FILE);
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor
                    .getLength());
            player.setLooping(true);
            player.prepare();

            player.seekTo(currentPosition);


            int result = audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
                @Override
                public void onAudioFocusChange(int focusChange) {
                    HT_Log.d(TAG, "onAudioFocusChange->" + focusChange);
                    if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                        // Pause playback
                        player.pause();
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
//                    am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
//                    am.abandonAudioFocus(afChangeListener);
                        // Stop playback
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                        // Lower the volume
                    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                        // Resume playback or Raise it back to normal
                        player.start();
                    }
                }
            }, streameType, AudioManager.AUDIOFOCUS_GAIN);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                player.start();
            }

            isPlaying = true;
        } catch (Exception e) {
            HT_Log.e(TAG, e);
            stop();
        }

    }

    public void stop() {
        HT_Log.d(TAG, "stopRinging:" + isPlaying);
        try {

            if (player != null) {
                player.stop();
                player.release();
            }
        } catch (Exception e) {
            HT_Log.e(TAG, e);
        } finally {
            player = null;
            isPlaying = false;
            audioManager.setSpeakerphoneOn(true);
            audioManager.setMode(AudioManager.MODE_NORMAL);
            audioManager.abandonAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
                @Override
                public void onAudioFocusChange(int focusChange) {
                    HT_Log.d(TAG, "onAudioFocusChange->" + focusChange);
                }
            });
        }
    }


    public void openSpeaker(Activity ctx) {
        try {
            isSpeakerOn = true;
            if (player != null) {
                currentPosition = player.getCurrentPosition();
            }
            HT_Log.d(TAG, "openSpeaker");
            stop();
            play(ctx);

            ctx.setVolumeControlStream(AudioManager.STREAM_RING);
        } catch (Exception e) {
            HT_Log.e(TAG, e);
        }
    }

    public void closeSpeaker(Activity ctx) {
        try {
            isSpeakerOn = false;
            if (player != null) {
                currentPosition = player.getCurrentPosition();
            }
            HT_Log.d(TAG, "closeSpeaker");
            stop();
            play(ctx);

            ctx.setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
